package com.edu.javaproect.service;

import com.alibaba.fastjson.JSONObject;
import com.edu.javaproect.Constants;
import com.edu.javaproect.bean.HotVideoRpc;
import com.edu.javaproect.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:秇稔
 * @email:2580108178@qq.com
 * @Date:2021/12/17 11:33
 * @desc：该类用于调用比特币的rpc功能，获取最新区块的哈希值
 **/
public class GetBestBlockHashService {
    public String getBestBlockHash(){
        //准备用户消息
        String author = Constants.BITCOIN_RPC_USER + ":" + Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());

        //准备请求头消息
        Map<String , String> header = new HashMap<>();
        header.put("ContentType" , "application/json");
        header.put("Authorization" , "Basic " + authorBase64);

        //准备请求的数据
        Map<String , Object> body = new HashMap<>();
        body.put("id" ,1001);
        body.put("method" , "getbestblockhash");
        body.put("params" , null);
        body.put("json_rpc" , "2.0");
        //将map转换为byte[]
        byte[] bodyBytes = JSONObject.toJSONBytes(body);

        //result返回的是 rpc 的响应格式
        String result =  HttpUtils.post(Constants.BITCOIN_RPC_URL , header , bodyBytes);
        //对result进行json反序列化
        HotVideoRpc hotVideoRpc = JSONObject.parseObject(result, HotVideoRpc.class);

        return hotVideoRpc.result;
    }
    public String getBlockCount(){
        //准备用户消息
        String author = Constants.BITCOIN_RPC_USER + ":" + Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());

        //准备请求头消息
        Map<String , String> header = new HashMap<>();
        header.put("ContentType" , "application/json");
        header.put("Authorization" , "Basic " + authorBase64);

        //准备请求的数据
        Map<String , Object> body = new HashMap<>();
        body.put("id" ,1000);
        body.put("method" , "getblockcount");
        body.put("params" , null);
        body.put("json_rpc" , "2.0");
        //将map转换为byte[]
        byte[] bodyBytes = JSONObject.toJSONBytes(body);

        //result返回的是 rpc 的响应格式
        String result =  HttpUtils.post(Constants.BITCOIN_RPC_URL , header , bodyBytes);
        //对result进行json反序列化
        HotVideoRpc hotVideoRpc = JSONObject.parseObject(result, HotVideoRpc.class);
        return hotVideoRpc.result;
    }
}
